<script lang="jsx" setup>
import { ref, watch } from 'vue';

const props = defineProps({
  operationType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: () => null
  },
  formOptions: {
    type: Array,
    default: () => []
  }
});

console.log(props.operationType);

const col = ref(24);

watch(
  () => props.operationType,
  val => {
    console.log(val);

    if (props.operationType === 'add') {
      col.value = 24;
    } else {
      col.value = 0;
    }
  }
);

const formRef = ref(null);
const formList = ref([
  {
    type: 'select',
    key: 'form',
    label: '点检关联表单',
    placeholder: '请选择点检关联表单',
    span: 24,
    search: true,
    selectOptions: props.formOptions,
    change(val) {
      model.value.inspectionFormId = props.formOptions.find(k => k.value === val).id;
    }
  },
  {
    type: 'input',
    key: 'inspectionMachineName',
    label: '设备名称',
    placeholder: '请输入设备名称',
    span: props.operationType === 'bindForm' ? 0 : 24,
    rule: {
      required: true,
      message: '请输入设备名称',
      trigger: 'change'
    }
  },
  {
    type: 'input',
    key: 'inspectionMachineCode',
    label: '设备编号',
    placeholder: '请输入设备编号',
    span: props.operationType === 'bindForm' ? 0 : 24,
    rule: {
      required: true,
      message: '请输入设备编号',
      trigger: 'change'
    }
  },
  {
    type: 'input',
    key: 'inspectionMachineDept',
    label: '设备部门',
    placeholder: '请输入设备部门',
    span: props.operationType === 'bindForm' ? 0 : 24,
    rule: {
      required: true,
      message: '请输入设备部门',
      trigger: 'change'
    }
  },
  {
    type: 'input',
    key: 'inspectionMachineNo',
    label: '设备机台号',
    placeholder: '请输入设备机台号',
    span: props.operationType === 'bindForm' ? 0 : 24,
    rule: {
      required: true,
      message: '请输入设备机台号',
      trigger: 'change'
    }
  }
]);

const model = ref({ ...getModel() });

function getModel() {
  const data = {
    inspectionFormId: null
  };
  formList.value.forEach(item => {
    if (item.key === 'form') {
      if (props.rowData?.inspectionFormId) {
        data[item.key] = props.formOptions.find(k => k.id === props.rowData.inspectionFormId).value;
        data.inspectionFormId = props.rowData.inspectionFormId;
      } else {
        data[item.key] = null;
      }
    } else {
      data[item.key] = props.rowData?.[item.key] || null;
    }
  });

  return data;
}

async function validateForm() {
  await formRef.value.validateForm();
}

defineExpose({
  model: model.value,
  validateForm
});
</script>

<template>
  <Form
    ref="formRef"
    v-model:model="model"
    :form-list="formList"
    :class="props.operationType === 'bindForm' ? 'bind-form' : 'add-form'"
  ></Form>
</template>

<style lang="scss" scoped>
.add-form {
  height: 285px;
}

.bind-form {
  height: 50px;
}
</style>
